package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SkusHasStockVo;
import com.atguigu.common.to.SupBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareSkuFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareSkuFeignService wareSkuFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    /**
     * 根据查询条件查询spu信息
     * status: 0
     * * key: 11
     * * brandId: 1
     * * catelogId: 225
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<java.lang.String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
//        得到查询条件
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().eq("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 新增商品
     *
     * @param spuInfoVo
     * @TODO 需要完善，这些都是成功的响应，要是失败了如何处理
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfoVo) {
//        1、保存spu基本信息 pms_sku_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);
//          1.1、把实体与spuInfoVo对应的字段没有的值填上
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

//        2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = spuInfoVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
//            2.1、把商品id与商品介绍保存
//              注意：这里虽然是设置进spuId，但是mysql以为是自增的，所以没有增加id，改变实体类中的id注解
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

//        3、保存Spu的图片集 pms_spu_images
        List<String> images = spuInfoVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

//        4、保存Spu的规格参数 pms_product_attr_value
//            4.1、得到页面传过来的所有基本属性
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
//            4.2、得到属性id，属性值，是否快速展示
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
//            设置属性的名称
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(collect);

//        5、保存Spu积分信息 gulimall-sms -> sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SupBoundTo supBoundTo = new SupBoundTo();
        BeanUtils.copyProperties(bounds, supBoundTo);
        supBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(supBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

//        6、保存当前spu对应的所有sku信息
        List<Skus> skus = spuInfoVo.getSkus();
        if (null != skus && skus.size() > 0) {
            skus.forEach(sku -> {
//          6.1、sku的基本信息：pms_sku_info
//                得到图片路径
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) { //是一个默认图片
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
//             把sku中没有的字段值，通过其他手段获取，设置到skuInfoEntity实体中
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

//          6.2、sku的图片信息：pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
//                得到所有图片信息
                List<SkuImagesEntity> imagesEntitys = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
//                    过滤掉不需要的
                }).filter(entity -> {
//                    返回true就是需要的，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntitys);

//          6.3、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
//                    拼装前端返回数据中没有的字段。即：a中没有的字段，但skuSaleAttrValueEntity有的字段
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

//          6.4、sku的优惠，减满等信息：gulimall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r1.getCode() != 0) {
                    log.error("远程保存sku满减和打折信息失败");
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * 商品上架功能
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
//        1、组装数据
        List<SkuEsModel> skuEsModels = new ArrayList<>();

//        1.1、根据spuId查找所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

//        得到skuIds
        List<Long> skuIds = skus.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());

//        远程调用库存服务,查看是否有库存
        Map<Long, Boolean> hasStockMap = null;
        try {
            R r = wareSkuFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkusHasStockVo>> typeReference = new TypeReference<List<SkusHasStockVo>>() {
            };
//            TODO 可能有問題
            hasStockMap = r.getData(spuId.toString(), typeReference).stream().collect(Collectors.toMap(SkusHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("远程调用库存数量服务异常：" + e);
        }

        /**
         * 1.3、查询当前商品所有规格属性值，还得查询出能被检索的属性
         */
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseListforspu(spuId);
//            得到所有属性id
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
//          根据所有属性id查找能被检索的所有属性,需要转换成set，因为有重复的
        List<Long> searchAttrs = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrs);
//        如果能被检索的所有属性在所有规格属性中，那么就是我们需要的数据
        List<SkuEsModel.Attrs> attrs = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        Map<Long, Boolean> finalHasStockMap = hasStockMap;
//        1.2、把查询出来的sku信息对拷到skuEsModel中
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
//            把sku中没有skuEsModel的属性设置进去
            /**
             * skuPrice，skuImg，hasStock，hotScore，brandName，brandImg，catalogName，attrs.
             */
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            /**
             * 是否拥有库存，有则true，无则false,如果每次调用远程服务，一次需要调用8+次
             * 需要远程调用库存服务ware,远程返回库存量和skuId
             */
            if (null == finalHasStockMap) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalHasStockMap.get(sku.getSkuId()));
            }

//            TODO 热度评分，默认设置为0，后续再完善功能
            skuEsModel.setHotScore(0L);
//            品牌名称根据品牌id去查找
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
//            分类名称
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

//            查询当前规格属性
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

//        调用es远程服务 gulimall-search 把数据发送给es，最后展示在客户端。
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
//            远程调用成功，修改当前spu状态(根据当前spuId与上架状态)
            this.baseMapper.updateStatusById(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
//            上架失败,
        }
//            TODO 调用成功后，接口幂等性（重复调用问题）
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(byId.getSpuId());
        return spuInfoEntity;
    }
}
